package appapi.controller.oider;

import appapi.Global.BusinessException;
import appapi.common.ResponseBean;
import appapi.model.ResponseDataModel;
import appapi.model.ResponseModel;
import appapi.service.impl.LocalStorageService;
import appapi.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Api(value = "/api/File", tags = "客户端文件相关")
@RestController
@RequestMapping(value = "/api/File")
public class FileController {
    @Autowired
    private LocalStorageService localStorageService;

    @RequestMapping(value = "/download")
    public void download(@RequestParam("fileName") String filename) throws IOException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        // 设置信息给客户端不解析
        String type = new MimetypesFileTypeMap().getContentType(filename);
        // 设置contenttype，即告诉客户端所发送的数据属于什么类型
        response.setHeader("Content-type", type);
        // 设置编码
        String hehe = new String(filename.getBytes("utf-8"), "iso-8859-1");
        // 设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
        response.setHeader("Content-Disposition", "attachment;filename=" + hehe);
        FileUtil.download(filename, response);
    }

    @ApiOperation(value = "图片上传", notes = "图片上传")
    @PostMapping(value = "/upload")
    @ResponseBody
    public ResponseDataModel upload(Integer type, @RequestParam("file") MultipartFile file) throws IOException {
        ResponseDataModel responseModel = new ResponseDataModel();
        try {
            if (file.isEmpty()) {
                throw new RuntimeException("上传文件不能为空");
            }
            String filePath = localStorageService.upload(type, file);
            responseModel.setData(filePath);
            responseModel.setMessage(filePath);
        } catch (Exception e) {
            responseModel.setCode(-1);
            responseModel.setMessage(e.getMessage().concat("文件上传失败: " + e.getMessage()));
        }
        return responseModel;
    }
}
